<script setup>
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { ref, nextTick } from 'vue'
	import { getOrder, cancelOrder, payOrder, confirmOrder, delOrder } from '@/api/shop'
	import { parseTime } from '@/utils/common'
	
	const config = getApp().globalData.config
	const buttonStyle = ref({width: '160rpx'})
	const loading = ref(false)
	const form = ref({
		status: '',
		list: []
	})
	const codeArr = ref([])
	const timeData = ref({})
	const qrCodePopup = ref(null)
	const qrcodeEle = ref(null)
	const qrcodeOptions = {foregroundImageSrc: config.appInfo.logo}
	const cancelModal = ref(null)
	const urgeModal = ref(null)
	const confirmModal = ref(null)
	const delModal = ref(null)
	const pickUpPopup = ref(null)
	
	function getData(id) {
		loading.value = true
		getOrder(id).then(res => {
			let result = res.result || {list: []}
			result.list.forEach(item => item.expand = false)
			if(result.status === 1 && result.type !== 'INTEGRAL') {
				result.countdown = computeCountTime(parseTime(result.createTime, '{y}/{m}/{d} {h}:{i}:{s}'))
			}
			form.value = result
			loading.value = false
		}).catch(() => loading.value = false)
	}
	function contact() {
		uni.makePhoneCall({
			phoneNumber: '18200000000'
		})
	}
	function navigation() {
		uni.openLocation({
			latitude: 30.057367,
			longitude: 103.190645,
			name: '茗山总仓'
		})
	}
	function changeDetailExpand(item) {
		item.expand = !item.expand
	}
	function statusToText(value) {
		switch(value) {
			case 0: return '已关闭';
			case 1: return '待付押金';
			case 2: return '待受理';
			case 3: return '待分拣';
			case 4: return '待出库';
			case 5: return '待发货';
			case 6: return '待收货';
			case 7: return '待确认';
			case 8: return '待付尾款';
			case 9: return '已完成';
			default: return '未知'
		}
	}
	function salesToText(value) {
		switch(value) {
			case 1: return '售后中';
			case 2: return '售后通过';
			case 3: return '售后驳回';
			default: return '未知'
		}
	}
	function qrCode() {
		qrCodePopup.value.open()
		setTimeout(() => {
			qrcodeEle.value.make()
		}, 200)
	}
	function confirmeQrCode() {
		qrcodeEle.value.save({
			success: () => {
				uni.showToast({icon: 'success', title: '保存成功'})
				closeQrCode()
			},
			fail: () => {
				uni.showToast({icon: 'none', title: '保存失败'})
			}
		})
	}
	function closeQrCode() {
		qrCodePopup.value.close()
	}
	function cancel() {
		cancelModal.value.open()
	}
	function confirmCancel() {
		loading.value = true
		cancelOrder(form.value.orderId).then(res => {
			loading.value = false
			uni.showToast({icon: 'success', title: '取消成功'})
			setTimeout(() => {
				getData(form.value.orderId)
				closeCancel()
			}, 200)
		}).catch(() => loading.value = false)
	}
	function closeCancel() {
		
	}
	function pay(successStatus = 1) {
		loading.value = true
		payOrder(form.value.orderId).then(res => {
			loading.value = false
			let data = res.result
			let info = {
				status: successStatus,
				addrName: form.value.logisticsType === 2? form.value.receiverDetailAddress : '茗山总仓（某某小学附近）',
				addr: form.value.logisticsType === 2? form.value.receiverAddress : '四川省雅安市茗山区前进镇桥楼村99号',
				expectedTime: form.value.expectedTime,
				logisticsType: form.value.logisticsType
			}
			if(data) {
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: data.timeStamp,
					nonceStr: data.nonceStr,
					package: data.packageVal,
					signType: data.signType,
					paySign: data.paySign,
					success: (data) => {
						info.status = successStatus + 1
						let params = JSON.stringify(info)
						uni.redirectTo({
							url: '/pages/shop/orderPay?params='+ params,
						})
					},
					fail: (err) => {
						let params = JSON.stringify(info)
						uni.redirectTo({
							url: '/pages/shop/orderPay?params='+ params,
						})
					}
				})
			} else {
				info.status = successStatus + 1
				let params = JSON.stringify(info)
				uni.redirectTo({
					url: '/pages/shop/orderPay?params='+ params,
				})
				user.getInfoAction()
			}
			
		}).catch(() => loading.value = false)
	}
	function sales() {
		uni.navigateTo({
			url: '/pages/shop/orderSales?id=' + form.value.orderId
		})
	}
	function urge() {
		urgeModal.value.open()
	}
	function confirmUrge() {
		uni.showToast({icon: 'success', title: '催促成功'})
		closeUrge()
	}
	function closeUrge() {
		
	}
	function confirm() {
		confirmModal.value.open()
	}
	function confirmConfirm() {
		loading.value = true
		confirmOrder(form.value.orderId).then(res => {
			loading.value = false
			uni.showToast({icon: 'success', title: '确认成功'})
			setTimeout(() => {
				getData(form.value.orderId)
				closeConfirm()
			}, 0)
		}).catch(() => loading.value = false)
	}
	function closeConfirm() {
		
	}
	function pickUp() {
		codeArr.value = form.value.deliveryCode.split('')
		pickUpPopup.value.open()
	}
	function confirmPickUp() {
		closePickUp()
	}
	function closePickUp() {
		codeArr.value = []
		pickUpPopup.value.close()
	}
	function del() {
		delModal.value.open()
	}
	function confirmDel() {
		loading.value = true
		delOrder(form.value.orderId).then(res => {
			loading.value = false
			uni.showToast({icon: 'success', title: '删除成功'})
			setTimeout(() => {
				uni.navigateBack()
				closeDel()
			}, 200)
		}).catch(() => loading.value = false)
	}
	function closeDel() {
		
	}
	function again(id) {
		
	}
	function copy() {
		uni.setClipboardData({
			data: form.value.code,// 要被复制的内容
			success: () => {
				uni.showToast({
					icon: 'none',
					title: '复制成功'
				})
			}
		})
	}
	function computeCountTime(timeStr) {
		let nowTimeStamp = +new Date()
		let endTimeStamp = +new Date(timeStr) + 15 * 60 * 1000
		let seconds = endTimeStamp - nowTimeStamp
		return seconds > 0? seconds : 0
	}
	function countFinish() {
		form.value.countdown = 0
		form.value.status = 0
	}
	onLoad((option) => {
		let id = option.id
		if(id) getData(id)
	})
	onShow(() => {
		if(form.value.orderId) {
			getData(form.value.orderId)
		}
	})
</script>

<template>
	<view class="app-container">
		<view class="app-content">
			<view class="status-box">
				<view class="pay-status" v-if="form.status === 1">
					<view class="status-info status-title">
						<uv-icon name="clock" color="#328BFF" size="50" />
						<text>等待付押金</text>
						<uv-count-down :time="form.countdown" format="mm:ss" @finish="countFinish" v-if="form.countdown"></uv-count-down>
					</view>
					<view class="status-tip">现在支付，最早可于{{parseTime(form.expectedTime, '{m}月{d}日')}}后提货</view>
				</view>
				<view class="pay-status" v-else-if="form.status === 2">
					<view class="status-info status-title">
						<uv-icon name="checkmark-circle" color="#328BFF" size="50" />
						<text>支付押金成功</text>
					</view>
					<view class="status-tip">下单成功，最早可于{{parseTime(form.expectedTime, '{m}月{d}日')}}后取货</view>
				</view>
				<view class="pay-status" v-else-if="form.status === 3">
					<view class="status-info status-title">
						<uv-icon name="checkmark-circle" color="#328BFF" size="50" />
						<text>商品准备中</text>
					</view>
					<view class="status-tip">商品正在等待打包，最早可于{{parseTime(form.expectedTime, '{m}月{d}日')}}后取货</view>
				</view>
				<view class="pay-status" v-else-if="form.status === 7">
					<uv-image src="https://jhgk-1307466921.cos.ap-shanghai.myqcloud.com/opt/AppCollect/PersonJkzImg/2024-11-18/1731915302994_registerSuccess.png"
						width="330" height="234"></uv-image>
					<text class="status-title">提货成功</text>
					<view class="status-tip">感谢使用相宴商城</view>
				</view>
				<view class="pay-status" v-else-if="form.status === 8">
					<view class="status-info status-title">
						<uv-icon name="clock" color="#328BFF" size="50" />
						<text>等待付尾款</text>
					</view>
					<view class="status-tip">请尽快支付尾款</view>
				</view>
				<view class="pay-status" v-else>
					<view class="status-info status-title">
						<uv-icon name="clock" color="#328BFF" size="50" />
						<text>订单{{form.saleStatus? salesToText(form.saleStatus) : statusToText(form.status)}}</text>
					</view>
				</view>
				<view class="tip-box"><uv-icon name="question-circle" color="#FF662F" size="30" bold /><text>购物中心如有问题，可联系客服进行解决~</text></view>
			</view>
			<view class="box-view">
				<view class="accept-user">
					<text class="label">提货人：</text>
					<text class="value">{{form.receiverBy || '--'}} {{form.receiverPhone || '--'}}</text>
				</view>
				<view class="accept-address border-top" v-if="form.logisticsType === 2">
					<view class="label">取货地点：{{form.receiverDetailAddress || '--'}}</view>
					<view class="value">{{form.receiverAddress || '--'}}</view>
				</view>
				<view class="accept-address border-top" v-else>
					<view class="label">自提点：茗山总仓（某某小学附近）</view>
					<view class="value">四川省雅安市茗山区前进镇桥楼村</view>
				</view>
				<view class="accept-info border-top">
					<view class="contact" @click="contact"><uv-icon name="phone-fill" color="#10B02D" size="30" /><text>联系客服</text></view>
					<view class="navigation" v-if="form.logisticsType === 4" @click="navigation">
						<uv-icon name="map-fill" color="#328BFF" size="30" />
						<text>导航前往</text>
					</view>
				</view>
			</view>
			<view class="box-view" v-if="form.list && form.list.length">
				<view v-for="item in form.list" :key="item.itemId" class="good-box">
					<goods v-model="item.num" :img="item.image && item.image.furl" :name="item.name" :price="item.price" :total="item.subtotal" :specs="item.specs"
					:mode="form.type === 'INTEGRAL'? 'viewPL' : 'view'"></goods>
					<view class="goods-detail" v-if="item.type === 'DISHES' || item.type === 'DEVICE'">
						<template v-if="item.list && item.list.length">
							<view class="goods-detail-box" v-if="item.expand">
								<view class="goods-detail-item" v-for="child in item.list" :key="child.id">
									<goods v-model="child.num" :img="child.image && child.image.furl" :name="child.name" :price="child.price" :specs="child.specs"
										mode="viewD" v-if="child.name"></goods>
									<goods v-model="child.num" mode="invalidD" v-else></goods>
								</view>
							</view>
						</template>
						<view class="goods-detail-expand" @click="changeDetailExpand(item)">
							<text class="more-text">{{ item.expand? '收起' : '查看明细详情'}}</text>
							<uv-icon :name="item.expand? 'arrow-up-fill' : 'arrow-down-fill'" color="#4E5969" size="24"></uv-icon>
						</view>
					</view>
				</view>
			</view>
			<view class="box-view" v-if="form.type === 'COMBINATION'">
				<view class="info-row">
					<view class="lable">乡厨服务费：</view>
					<view class="value red text-price">{{form.serviceCharge? form.serviceCharge.toFixed(2) : 0.00}}</view>
				</view>
			</view>
			<view class="box-view">
				<view class="info-row border-bottom">
					<view class="lable">商品总额：</view>
					<view class="value">
						<text class="text-points" v-if="form.type === 'INTEGRAL'">{{form.total || 0}}</text>
						<text class="text-price" v-else>{{form.total? form.total.toFixed(2) : 0.00}}</text>
					</view>
				</view>
				<view class="info-row border-top" v-if="form.type === 'COMBINATION'">
					<view class="lable">餐车优惠：</view>
					<view class="value red">-<text class="text-price">{{form.foodSubDeviceAmount? form.foodSubDeviceAmount.toFixed(2) : 0.00}}</text></view>
				</view>
				<view class="info-row" v-if="form.type != 'INTEGRAL'">
					<view class="lable">优惠券：</view>
					<view class="value red">-<text class="text-price">{{form.couponAmount? form.couponAmount.toFixed(2) : 0.00}}</text></view>
				</view>
				<view class="info-row border-top" v-if="form.type !== 'INTEGRAL'">
					<view class="lable">支付押金：</view>
					<view class="value">
						<text class="text-price">{{form.depositAmount? form.depositAmount.toFixed(2) : 0.00}}</text>
					</view>
				</view>
				<view class="info-row border-top">
					<view class="lable">实际支付：</view>
					<view class="value">
						<text class="text-points" v-if="form.type === 'INTEGRAL'">{{form.payAmount || 0}}</text>
						<text class="text-price" v-else>{{form.payAmount? form.payAmount.toFixed(2) : 0.00}}</text>
					</view>
				</view>
			</view>
			<view class="box-view">
				<view class="info-row">
					<view class="lable">备注：</view>
					<view class="value gray">{{form.remark || '--'}}</view>
				</view>
			</view>
			<view class="box-view">
				<view class="info-row">
					<view class="lable">订单号：</view>
					<view class="value">
						<text class="gray">{{form.code || '--'}}</text>
						<text class="copy-btn" @click="copy">复制</text>
					</view>
				</view>
				<view class="info-row border-top">
					<view class="lable">下单时间：</view>
					<view class="value">{{form.createTime || '--'}}</view>
				</view>
			</view>
		</view>
		<view class="app-bottom theme-btn">
			<uv-button color="#606060" shape="circle" size="small" :custom-style="buttonStyle" text="联系平台" @click="contact"
				:disabled="loading" :plain="true" v-if="form.saleStatus"></uv-button>
			<template v-else>
				<uv-button color="#606060" shape="circle" size="small" :custom-style="buttonStyle" text="订单二维码" @click="qrCode"
					:disabled="loading" :plain="true"></uv-button>
				<uv-button color="#606060" shape="circle" size="small" :custom-style="buttonStyle" text="取消订单" @click="cancel"
					:disabled="loading" :plain="true" v-if="form.status === 1"></uv-button>
				<uv-button color="#FF3E49" shape="circle" size="small" :custom-style="buttonStyle" text="付押金" @click="pay(1)"
					:disabled="loading" v-if="form.status === 1"></uv-button>
				<uv-button color="#606060" shape="circle" size="small" :custom-style="buttonStyle" text="申请售后" @click="sales" 
					:disabled="loading" :plain="true" v-if="[2,3,4,5,6,7].includes(form.status) || form.saleStatus === 3"></uv-button>
				<uv-button color="#FF3E49" shape="circle" size="small" :custom-style="buttonStyle" text="付尾款" @click="pay(3)"
					:disabled="loading" v-if="form.status === 8"></uv-button>
				<uv-button color="#606060" shape="circle" size="small" :custom-style="buttonStyle" text="催促发货" @click="urge"
					:disabled="loading" :plain="true" v-if="[2,3,4,5].includes(form.status)"></uv-button>
				<uv-button color="#FF3E49" shape="circle" size="small" :custom-style="buttonStyle" text="取货码" @click="pickUp"
					:disabled="loading" v-if="form.status === 6"></uv-button>
				<uv-button color="#FF3E49" shape="circle" size="small" :custom-style="buttonStyle" text="确认收货" @click="confirm"
					:disabled="loading" v-if="form.status === 7"></uv-button>
				<uv-button color="#606060" shape="circle" size="small" :custom-style="buttonStyle" text="删除订单" @click="del"
					:disabled="loading" :plain="true" v-if="form.status === 9|| form.status === 0"></uv-button>
			</template>
			<!-- <uv-button color="#FF3E49" shape="circle" size="small" :custom-style="buttonStyle" text="再次购买" @click="again()"
				:disabled="loading" v-if="form.status === 5"></uv-button> -->
		</view>
		
		<uv-modal ref="cancelModal" @confirm="confirmCancel" @cancel="closeCancel" confirmColor="#FF3E49" showCancelButton>
			<view class="modal-content">确定取消订单吗?</view>
		</uv-modal>
		<uv-modal ref="urgeModal" @confirm="confirmUrge" @cancel="closeUrge" confirmColor="#FF3E49" showCancelButton>
			<view class="modal-content">确定催促发货吗?</view>
		</uv-modal>
		<uv-modal ref="confirmModal" @confirm="confirmUrge" @cancel="closeConfirm" confirmColor="#FF3E49" showCancelButton>
			<view class="modal-content">确定收货?</view>
		</uv-modal>
		<uv-modal ref="delModal" @confirm="confirmDel" @cancel="closeDel" confirmColor="#FF3E49" showCancelButton>
			<view class="modal-content">确定删除订单吗?</view>
		</uv-modal>
		
		<uv-popup ref="qrCodePopup" closeable mode="center" bgColor="none">
			<view class="popup-box">
				<view class="popup-title">订单二维码</view>
				<view class="popup-content">
					<view class="qrcode-box">
						<uv-qrcode ref="qrcodeEle" :value="form.associateCode" :options="qrcodeOptions" :start="false" :hide="!form.associateCode"></uv-qrcode>
						<empty text="订单编码不存在" :srcSize="300" v-if="!form.associateCode"></empty>
					</view>
				</view>
				<view class="popup-bottom">
					<uv-button shape="circle" :custom-style="{width: '295rpx', background: '#ffffff', border: '2rpx solid #FF1313', color: '#FF1313'}"
						text="取消" @click="closeQrCode"></uv-button>
					<uv-button color="linear-gradient(102deg, #FA3F00 0%, #FF7445 100%)" shape="circle" :custom-style="{width: '295rpx'}" text="保存"
						@click="confirmeQrCode" v-if="form.associateCode"></uv-button>
				</view>
			</view>
		</uv-popup>
		<uv-popup ref="pickUpPopup" closeable mode="center" bgColor="none">
			<view class="popup-box">
				<view class="popup-title">取货码</view>
				<view class="popup-content">
					<view class="code-box">
						<view class="code-item">{{codeArr[0] || '-'}}</view>
						<view class="code-item">{{codeArr[1] || '-'}}</view>
						<view class="code-item">{{codeArr[2] || '-'}}</view>
						<view class="code-item">{{codeArr[3] || '-'}}</view>
					</view>
				</view>
				<view class="popup-bottom">
					<uv-button shape="circle" :custom-style="{width: '295rpx', background: '#ffffff', border: '2rpx solid #FF1313', color: '#FF1313'}"
						text="取消" @click="closePickUp"></uv-button>
					<uv-button color="linear-gradient(102deg, #FA3F00 0%, #FF7445 100%)" shape="circle" :custom-style="{width: '295rpx'}" text="确定"
						@click="confirmPickUp"></uv-button>
				</view>
			</view>
		</uv-popup>
	</view>
</template>

<style lang="scss" scoped>
	.app-container{
		padding-bottom: 120rpx;
		.app-content{
			padding: 24rpx;
			.status-box{
				border-radius: 16rpx;
				overflow: hidden;
				.success-box{
					padding: 32rpx;
					background-color: #FFFFFF;
					display: flex;
					flex-direction: column;
					align-items: center;
					gap: 32rpx;
				}
				.pay-status{
					padding: 32rpx;
					background-color: #FFFFFF;
					display: flex;
					flex-direction: column;
					align-items: center;
					gap: 16rpx;
					.status-info{
						display: flex;
						align-items: center;
						gap: 16rpx;
						::v-deep .uv-count-down__text{
							font-weight: 600;
							font-size: var(--theme-xl);
							line-height: var(--theme-xl-line);
							color: #FD1024;
						}
					}
					.status-tip{
						color: #767473;
						text-align: center;
					}
					.status-title{
						font-weight: 600;
						font-size: var(--theme-xl);
						line-height: var(--theme-xl-line);
					}
				}
				.tip-box{
					padding: 16rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					gap: 6rpx;
					color: #FF662F;
					background: rgba(255,102,47,0.1);
				}
			}
			.accept-user{
				padding: 32rpx 0;
				.label{
					font-weight: 600;
				}
				.value{
					color: #767473;
				}
			}
			.accept-address{
				padding: 24rpx 0;
				.label{
					font-weight: 600;
				}
				.value{
					margin-top: 16rpx;
					color: #767473;
				}
			}
			.accept-info{
				padding: 24rpx 0;
				display: flex;
				align-items: center;
				.contact{
					flex: 1;
					display: flex;
					justify-content: center;
					align-items: center;
					gap: 6rpx;
					color: #767473;
				}
				.navigation{
					flex: 1;
					display: flex;
					justify-content: center;
					align-items: center;
					gap: 6rpx;
					color: #767473;
				}
			}
			.good-box{
				padding: 24rpx 0;
			}
			.good-box + .good-box{
				border-top: 2rpx solid #F4F4F4;
			}
			.goods-detail {
				border-top: 2rpx solid #EAEAEA;
				font-size: 28rpx;
				.goods-detail-box{
					padding: 16rpx 0;
					display: flex;
					flex-direction: column;
					gap: 16rpx;
				}
				.goods-detail-expand {
					padding-top: 16rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					gap: 20rpx;
					color: #767473;
				}
				.goods-detail-box + .goods-detail-expand{
					border-top: 2rpx solid #EAEAEA;
				}
			}
			.info-row{
				padding: 32rpx 0;
				display: flex;
				gap: 8rpx;
				.lable{
					flex-shrink: 0;
					font-weight: 600;
				}
				.value{
					flex: 1;
					text-align: right;
				}
				.red{
					color: #FD1024;
				}
				.gray{
					color: #767473;
				}
				.text-price{
					font-weight: 600;
					font-size: var(--theme-lg);
					line-height: var(--theme-lg-line);
					&::before{
						content: "¥";
						font-size: 60%;
					}
				}
				.text-points{
					font-weight: 600;
					font-size: var(--theme-lg);
					line-height: var(--theme-lg-line);
					&::after{
						content: "积分";
					}
				}
				.copy-btn::before{
					content: " | ";
					font-size: 100%;
				}
			}
		}
		.box-view{
			margin-top: 24rpx;
			padding: 0 24rpx;
			border-radius: 16rpx;
			background-color: #FFFFFF;
		}
		.border-top{
			border-top: 2rpx solid #F4F4F4;
		}
		.border-bottom{
			border-bottom: 2rpx solid #F4F4F4;
		}
		.app-bottom{
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0rpx;
			height: 120rpx;
			padding: 0 24rpx;
			display: flex;
			justify-content: flex-end;
			align-items: center;
			gap: 16rpx;
			background-color: #FFFFFF;
			border-top: 2rpx solid #D7DBE1;
		}
		.popup-box{
			width: 686rpx;
			background: linear-gradient( 180deg, #F9E7E7 0%, #FFFFFF 24%);
			border-radius: 32rpx;
			padding: 32rpx;
			.popup-title{
				padding-bottom: 24rpx;
				font-weight: 600;
				font-size: var(--theme-lg);
				line-height: var(--theme-lg-line);
			}
			.popup-content{
				.code-box{
					margin-top: 14rpx;
					display: flex;
					justify-content: center;
					gap: 48rpx;
					font-size: 56rpx;
					color: #202020;
					.code-item{
						width: 112rpx;
						height: 112rpx;
						text-align: center;
						line-height: 112rpx;
						background-color: rgba(32,32,32,0.04);
						border-radius: 20rpx;
					}
				}
				.qrcode-box{
					margin-top: 14rpx;
					display: flex;
					justify-content: center;
				}
			}
			.popup-bottom{
				padding-top: 32rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				gap: 32rpx;
			}
		}
	}
</style>